package com.thermofisher.dsc.amanda.common.crud.controller;

import com.thermofisher.dsc.amanda.common.Query;
import com.thermofisher.dsc.amanda.common.crud.service.BaseService;
import com.thermofisher.dsc.amanda.model.response.BaseResponse;
import com.thermofisher.dsc.amanda.model.response.CountResponse;
import com.thermofisher.dsc.amanda.model.response.DataResponse;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author yunpeng.song
 */
public abstract class AbsBaseController<S extends BaseService, T> implements BaseController<T> {

    @Autowired
    protected S service;


    @PostMapping("/insert")
    @Override
    public BaseResponse insert(@RequestBody  T t) {
        service.create(t);
        return new BaseResponse();
    }

    @PutMapping
    @Override
    public BaseResponse update(@RequestBody T t) {
        service.update(t);
        return new BaseResponse();
    }

    @DeleteMapping
    @Override
    public BaseResponse delete(@RequestParam("id") Long id) {
        service.delete(id);
        return new BaseResponse();
    }

    @GetMapping
    @Override
    public BaseResponse getList(
        @RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        return service.getList(query);
    }

    @GetMapping("/count")
    @Override
    public CountResponse getListCount(
        @RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        int count = service.getListCount(query);
        return new CountResponse(count);
    }

    @GetMapping("/{id}")
    @Override
    public BaseResponse getById(@PathVariable("id") Long id) {
        T t = (T) service.getById(id);
        DataResponse response = new DataResponse(t);
        if (t == null) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            response.setMessage(HttpStatus.NO_CONTENT.getReasonPhrase());
        }
        return response;
    }

}
